<script setup>
import {ref, onMounted, computed} from 'vue'
import { sessionApi, saveTypeApi, proTypesApi, oneTypeApi, listTypesApi, sortTypeApi, treeTypesApi } from '@/commons/api'
import routes from '@/commons/router'
import Loader from '@/components/loader/Loader'
import { CScrollbar } from 'c-scrollbar'
import Msg from '@/components/message'
import Confirm from '@/components/confirm'
import TreeSel from '@/components/cascader/TreeSel'
import Upload from '@/components/upload/Upload'
import BrandSel from '@/components/business/BrandSel'

const loadShow = ref(false)

const curKind = 1

// 界面挂载前处理
onMounted(() => {
  // 获取用户会话信息
  checkAuth()
})

let myAuth = {
  saveAuth: false,
  procAuth: false
}
// checkAuth 获取权限
const checkAuth = async () => {
  loadShow.value = true
  try {
    const res = await sessionApi()
    if (res.code === import.meta.env.VITE_SUCCESS_CODE) {
      const userBtnCode = res.data.btnCodes
      myAuth = {
        saveAuth: userBtnCode.indexOf('1003020201') !== -1,
        procAuth: userBtnCode.indexOf('1003020202') !== -1
      }
      await list()
    } else {
      localStorage.removeItem("token")
      Msg({ kind: 'error', txt: res.msg })
      routes.replace('/login')
    }
    loadShow.value = false
  } catch (e) {
    loadShow.value = false
    Msg({ kind: 'error', txt: '系统错误，请联系管理员！' + e })
  }
}

const typeList = ref([])
const hasData = ref(false)
// list 列表展示
const list = async () => {
  const res = await listTypesApi({ kind: curKind })
  if(res.code === import.meta.env.VITE_SUCCESS_CODE) {
    typeList.value = res.data
    hasData.value = true
    idList.value = []
    checkList.value = []
    allCheck.value = false
    res.data.forEach(() => {
      checkList.value.push(false)
    })
  }
}

// 选择效果实现
const idList = ref([])
const checkList = ref([])
const allCheck = ref(false)
// checkAll 全选
const checkAll = () => {
  idList.value = []
  checkList.value = []
  allCheck.value = !allCheck.value
  if(allCheck.value) {
    typeList.value.forEach(item => {
      idList.value.push(item.typeId)
      checkList.value.push(true)
    })
  } else {
    typeList.value.forEach(() => {
      checkList.value.push(false)
    })
  }
}
// checkCurId 单选
const checkCurId = (idx, typeId) => {
  if(!checkList.value[idx]) {
    idList.value.push(typeId)
  } else {
    idList.value.splice(idList.value.findIndex(id => id === typeId), 1)
  }
  checkList.value[idx] = !checkList.value[idx]
}

const typeForm = ref({
  typeId: '',
  typeName: '',
  typeCode: '',
  kind: curKind,
  parentId: '',
  parentName: '',
  parentCode: '',
  sort: 0,
  logoId: '',
  logoName: '',
  logoUrl: '',
  brandIds: '',
  remarks: '',
  paramList: []
})
// add 新增
const showModal = ref(false)
const add = () => {
  treeTypes()
  showModal.value = true
}
// update 修改
const update = async (typeId) => {
  const res = await oneTypeApi({ typeId })
  if(res.code === import.meta.env.VITE_SUCCESS_CODE) {
    await treeTypes()
    typeForm.value = res.data
    logoRef.value = { id: res.data.logoId, name: res.data.logoName, url: res.data.logoUrl, thumb: res.data.logoUrl.replace('/img/', '/img/thumb/') }
    showModal.value = true
  } else {
    Msg({ kind: 'info', txt: '暂无内容' })
  }
}
// save 保存提交
const save = async () => {
  let typeName = typeForm.value.typeName
  let typeCode = typeForm.value.typeCode
  let parentId = typeForm.value.parentId
  if(typeName === '' || typeName.length > 50) {
    Msg({ kind: 'warn', txt: '名称不能为空，且长度不超过50个字符！' })
    return
  } else if(typeCode === '' || typeCode.length > 30) {
    Msg({ kind: 'warn', txt: '编码不能为空，且长度为30位的数字编码！' })
    return
  } else if(parentId === '' || parentId.length !== 21) {
    Msg({ kind: 'warn', txt: '请选择父级分类！' })
    return
  }
  loadShow.value = true
  typeForm.value.logoId = logoRef.value.id
  typeForm.value.logoName = logoRef.value.name
  typeForm.value.logoUrl = logoRef.value.url
  try {
    const res = await saveTypeApi(typeForm.value)
    if(res.code === import.meta.env.VITE_SUCCESS_CODE) {
      closeModal()
      await list()
      Msg({ kind: 'success', txt: '恭喜您，按钮信息保存成功！' })
    } else {
      Msg({ kind: 'error', txt: res.msg })
    }
    loadShow.value = false
  } catch (e) {
    loadShow.value = false
    Msg({ kind: 'error', txt: '系统错误，请联系管理员！' + e })
  }
}

// closeModal 关闭弹出层，并重置表单数据
const closeModal = () => {
  showModal.value = false
  typeForm.value = {
    typeId: '',
    typeName: '',
    typeCode: '',
    kind: curKind,
    parentId: '',
    parentName: '',
    parentCode: '',
    sort: 0,
    logoId: '',
    logoName: '',
    logoUrl: '',
    brandIds: '',
    remarks: '',
    paramList: []
  }
  logoRef.value = { id: '', name: '', url: '' }
}

// process 删除
const process = async(states) => {
  if(!idList || idList.value.length===0) {
    Msg({ kind: 'warn', txt: '请至少选择一项再删除！' })
    return
  }
  Confirm('确定要处理选中的数据吗？').then(() => {
    proTypes(states)
  }).catch(() => {
    Msg({ kind: 'info', txt: "取消处理选中的数据！" })
  })
}
// proTypes 删除实现，分离出来防止调用时异步报错
const proTypes = async (states) => {
  let ids = idList.value.join(',')
  loadShow.value = true
  try {
    const res = await proTypesApi({ kind: curKind, states, ids })
    if(res.code === import.meta.env.VITE_SUCCESS_CODE) {
      await list()
      Msg({ kind: 'success', txt: '恭喜您，商品分类处理成功！' })
    } else {
      Msg({ kind: 'error', txt: res.msg })
    }
    loadShow.value = false
  } catch (e) {
    loadShow.value = false
    Msg({ kind: 'error', txt: '系统错误，请联系管理员！' + e })
  }
}

// 获取菜单数
const treeRef = ref([])
const treeTypes = async () => {
  const res = await treeTypesApi({ kind: curKind })
  if(res.code === import.meta.env.VITE_SUCCESS_CODE && res.data) {
    treeRef.value = res.data
    treeRef.value.unshift({
      selId: '111111111111111111111',
      selName: '一级分类',
      selCode: '000000',
      parentId: '000000000000000000000',
      children: null
    })
  } else {
    treeRef.value.push({
      selId: '111111111111111111111',
      selName: '一级分类',
      selCode: '000000',
      parentId: '000000000000000000000',
      children: null
    })
  }
}

// setValue 为下拉框赋值
const setValue = (type) => {
  typeForm.value.parentId = type.selId
  typeForm.value.parentName = type.selName
  typeForm.value.parentCode = type.selCode
  // 调用排序接口
  sort(curKind, type.selId, type.selCode)
}

// sort 按钮排序
const sort = async (kind, parentId, parentCode) => {
  const res = await sortTypeApi({ kind, parentId })
  if(res.code === import.meta.env.VITE_SUCCESS_CODE) {
    typeForm.value.sort = res.data
    let code = ''
    if(res.data < 9) {
      code = '0' + res.data
    } else {
      code = res.data
    }
    if(parentCode === '000000') {
      typeForm.value.typeCode = code + '0000'
    } else if(parentCode.substring(2, 6) === '0000') {
      typeForm.value.typeCode = parentCode.substring(0, 2) + code + '00'
    } else if(parentCode.substring(4, 6) === '00') {
      typeForm.value.typeCode = parentCode.substring(0, 4) + code
    }
  }
}

// 获取图片路径
const logoRef = ref({ id: '', name: '', url: '' })
const setUrl = (kind, type, file) => {
  logoRef.value = file
}

const setBrand = (brandIds) => {
  typeForm.value.brandIds = brandIds.join(',')
}

const fmtState = computed(() => {
  return (states) => {
    let str
    switch (states) {
      case 1:
        str = '已启用'
        break;
      case 3:
        str = '已停用'
        break;
      default:
        str = '其它'
        break
    }
    return str
  }
})
</script>

<template>
  <div class="type-a">
    <div class="type-b">
      <div class="type-c">
        <div v-if="myAuth.saveAuth" class="btn-pi mr15" title="新增" @click="add"><i class="iconfont">&#xea2d;</i> 新增</div>
        <div v-if="myAuth.procAuth" class="btn-de mr15" title="删除" @click="process(2)"><i class="iconfont">&#xea45;</i> 删除</div>
        <div v-if="myAuth.procAuth" class="btn-ds mr15" title="启用" @click="process(1)"><i class="iconfont">&#xea30;</i> 启用</div>
        <div v-if="myAuth.procAuth" class="btn-dw mr15" title="停用" @click="process(3)"><i class="iconfont">&#xea2e;</i> 停用</div>
        <div class="btn-r mr15" title="刷新" @click="list(0, 1)"><i class="iconfont">&#xea8c;</i></div>
      </div>
      <div class="type-d"><i class="iconfont">&#xeaaa;</i> 当前位置：工作台 > 供应 > 商品管理 > 商品分类</div>
    </div>
    <div v-if="hasData">
      <table>
        <tbody>
          <tr>
            <th style="width: 5%;"><span @click="checkAll()" title="全选"><i :class="['iconfont', allCheck ? 'chked' : 'chk']" v-html="allCheck ? '&#xea3a;' : '&#xea46;'" /></span></th>
            <th style="width: 25%;">名称</th>
            <th style="width: 15%;">编码</th>
            <th style="width: 25%;">父类</th>
            <th style="width: 10%;">排序</th>
            <th style="width: 10%;">状态</th>
            <th style="width: 10%;">操作</th>
          </tr>
          <tr v-for="(curType, index) in typeList" :key="curType.typeId" class="tr-style">
            <td class="txt-center"><span @click="checkCurId(index, curType.typeId)" title="选择"><i :class="['iconfont', checkList[index] ? 'chked' : 'chk']" v-html="checkList[index]  ? '&#xe685;' : '&#xe686;'" /></span></td>
            <td><div :style="{'padding-left': curType.level*15+'px'}">{{ curType.typeName }}</div></td>
            <td class="txt-center">{{ curType.typeCode }}</td>
            <td class="txt-center">{{ curType.parentName }}[{{ curType.parentCode }}]</td>
            <td class="txt-center">{{ curType.sort }}</td>
            <td class="txt-center"><span :class="[curType.states===1 ? 'tag-s' : 'tag-e']">{{fmtState(curType.states)}}</span></td>
            <td class="txt-center">
              <span v-if="myAuth.saveAuth" class="cl-warn" title="修改" @click="update(curType.typeId)"><i class="iconfont">&#xea48;</i> 修 改</span>
            </td>
          </tr>
        </tbody>
      </table>
    </div>
    <div v-else class="no-data">暂无内容</div>

    <!-- 新增、修改弹出层 -->
    <transition name="fade-mod" appear>
      <div v-if="showModal" class="modal-backdrop">
        <c-scrollbar>
          <div class="modal" style="width: 600px;">
            <div class="modal-header">
              <div class="header-left"><i class="iconfont">&#xea54;</i> 保存信息</div>
              <div class="header-right" @click="closeModal"><i class="iconfont fs22">&#xea7f;</i></div>
            </div>
            <div class="modal-body">
              <div>
                <div class="ipt-title"><span class="required">*</span>父级分类</div>
                <tree-sel :tree-list="treeRef" :kind="1" :inboxed="false" :curName="typeForm.parentName!=='' ? typeForm.parentName+'['+typeForm.parentCode+']' : ''" pre-name="父级分类" @setValue="setValue" />
              </div>
              <div>
                <div class="ipt-title"><span class="required">*</span>编码</div>
                <div><input type="text" v-model="typeForm.typeCode" maxlength="10" placeholder="请输入编码" class="ipt" /></div>
              </div>
              <div>
                <div class="ipt-title"><span class="required">*</span>名称</div>
                <div><input type="text" v-model="typeForm.typeName" maxlength="50" placeholder="请输入名称" class="ipt" /></div>
              </div>
              <div>
                <div class="ipt-title"><span class="required">*</span>排序</div>
                <div><input type="number" v-model="typeForm.sort" maxlength="30" placeholder="请输入排序" class="ipt" /></div>
              </div>
              <div>
                <div class="ipt-title">图片</div>
                <upload :kind="1" :types="1" :file="logoRef" @setUrl="setUrl" />
              </div>
              <div>
                <div class="ipt-title">关联品牌</div>
                <brand-sel :kind="curKind" :brandIds="typeForm.brandIds" @setBrand="setBrand" />
              </div>
              <div>
                <div class="ipt-title">描述</div>
                <div><textarea v-model="typeForm.remarks" class="desc-txt"></textarea></div>
              </div>
            </div>
            <div class="modal-footer">
              <div class="btn-pi mr15" @click="save"><i class="iconfont">&#xea90;</i> 保存</div>
              <div class="btn-d" @click="closeModal"><i class="iconfont">&#xea4f;</i> 取消</div>
            </div>
          </div>
        </c-scrollbar>
      </div>
    </transition>
    <loader :loadShow="loadShow" />
  </div>
</template>

<style scoped>
.type-a {padding: 10px;}
.type-b {padding: 0 20px 10px 20px; display: flex; display: -webkit-flex;}
.type-c {display: inline-flex; display: -webkit-inline-flex;}
.type-d {flex-grow: 1; text-align: right; padding-top: 10px; color: #666;}
</style>